<template>
  <div class="page-wrap">
    <el-card shadow="never">
      <div class="toolbar">
        <h2>新增采购单</h2>
        <div class="actions">
          <el-button type="primary" @click="save">保存采购单</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </div>

      <el-form :model="headerForm" label-width="100px" class="mb-12">
        <el-form-item label="供应商">
          <el-select v-model="headerForm.supplierId" placeholder="选择供应商" filterable class="w-240">
            <el-option v-for="s in supplier.suppliers" :key="s.id" :label="s.name" :value="s.id" />
          </el-select>
          <span v-if="currentSupplierName" class="ml-8 text-muted">（{{ currentSupplierName }}）</span>
        </el-form-item>
        <el-form-item label="单据日期">
          <el-date-picker v-model="headerForm.billDate" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="headerForm.remark" placeholder="备注" />
        </el-form-item>
      </el-form>

      <div class="detail-toolbar">
        <el-button type="primary" @click="openMatrix">矩阵添加（款色尺码）</el-button>
        <el-button @click="addEmptyRow">新增一行</el-button>
      </div>

      <el-table :data="items" border stripe>
        <el-table-column type="index" width="60" />
        <el-table-column prop="code" label="编码" width="140">
          <template #default="{ row }"><el-input v-model="row.code" placeholder="SKU/编码" /></template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="160">
          <template #default="{ row }"><el-input v-model="row.name" placeholder="商品名称" /></template>
        </el-table-column>
        <el-table-column prop="styleNo" label="款号" width="140">
          <template #default="{ row }"><el-input v-model="row.styleNo" placeholder="款号" /></template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="140">
          <template #default="{ row }">
            <el-select v-model="row.color" filterable placeholder="选择颜色">
              <el-option v-for="c in dict.colors" :key="c" :label="c" :value="c" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="尺码" width="140">
          <template #default="{ row }">
            <el-select v-model="row.size" filterable placeholder="选择尺码">
              <el-option v-for="s in dict.sizes" :key="s" :label="s" :value="s" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="qty" label="数量" width="120">
          <template #default="{ row }"><el-input-number v-model="row.qty" :min="0" /></template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="140">
          <template #default="{ row }"><el-input-number v-model="row.price" :min="0" :precision="2" :step="0.1" /></template>
        </el-table-column>
        <el-table-column label="小计" width="140">
          <template #default="{ row }">{{ formatMoney(Number(row.qty||0) * Number(row.price||0)) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ $index }">
            <el-button size="small" type="danger" @click="removeRow($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="summary">
        <span>合计数量：<b>{{ totalQty }}</b></span>
        <span>合计金额：<b>¥{{ formatMoney(totalAmount) }}</b></span>
      </div>
    </el-card>

    <el-dialog v-model="matrixVisible" title="矩阵添加（款色尺码）" width="840px">
      <div class="matrix-head">
        <el-input v-model="matrixForm.styleNo" placeholder="款号" class="w-160" />
        <el-input v-model="matrixForm.code" placeholder="编码" class="w-160" />
        <el-input v-model="matrixForm.name" placeholder="名称" class="w-220" />
        <el-input-number v-model="matrixForm.price" :min="0" :precision="2" :step="0.1" />
      </div>
      <div class="matrix-pick">
        <div>
          <div class="subt">选择颜色</div>
          <el-checkbox-group v-model="matrixForm.colors">
            <el-checkbox v-for="c in dict.colors" :key="c" :label="c" />
          </el-checkbox-group>
        </div>
        <div>
          <div class="subt">选择尺码</div>
          <el-checkbox-group v-model="matrixForm.sizes">
            <el-checkbox v-for="s in dict.sizes" :key="s" :label="s" />
          </el-checkbox-group>
        </div>
      </div>
      <el-table :data="matrixForm.colors" border stripe class="mt-12">
        <el-table-column label="颜色" width="120">
          <template #default="{ row }">{{ row }}</template>
        </el-table-column>
        <el-table-column v-for="sz in matrixForm.sizes" :key="sz" :label="sz">
          <template #default="{ row }">
            <el-input-number v-model="matrixQtyMap[`${row}__${sz}`]" :min="0" />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="matrixVisible=false">取消</el-button>
        <el-button type="primary" @click="applyMatrix">添加到明细</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { usePurchaseStore } from '@/stores/purchase.js'
import { useSupplierStore } from '@/stores/supplier.js'
import { useDictStore } from '@/stores/dict.js'

const purchase = usePurchaseStore()
const supplier = useSupplierStore()
const dict = useDictStore()

onMounted(() => {
  purchase.initialize()
  supplier.initialize()
  dict.initialize()
})

const headerForm = reactive({
  supplierId: '',
  billDate: new Date().toISOString().slice(0,10),
  remark: '',
})

const items = ref([])

const currentSupplierName = computed(() => {
  const s = supplier.suppliers.find(x => x.id === headerForm.supplierId)
  return s?.name || ''
})

function addEmptyRow(){
  items.value.push({ code:'', name:'', styleNo:'', color:'', size:'', qty:0, price:0 })
}
function removeRow(index){
  if (index < 0 || index >= items.value.length) return
  items.value.splice(index, 1)
}

const totalQty = computed(() => items.value.reduce((s, it) => s + Number(it.qty || 0), 0))
const totalAmount = computed(() => items.value.reduce((s, it) => s + Number(it.qty || 0) * Number(it.price || 0), 0))

function formatMoney(n){
  return Number(n || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function resetForm(){
  headerForm.supplierId = ''
  headerForm.billDate = new Date().toISOString().slice(0,10)
  headerForm.remark = ''
  items.value = []
}

function save(){
  if (!headerForm.supplierId) { ElMessage.warning('请选择供应商'); return }
  if (!items.value.length) { ElMessage.warning('请添加明细'); return }
  const s = supplier.suppliers.find(x => x.id === headerForm.supplierId)
  const payload = {
    supplierId: headerForm.supplierId,
    supplierName: s?.name || '',
    billDate: headerForm.billDate,
    remark: headerForm.remark,
    items: items.value,
    operator: '系统',
  }
  const bill = purchase.createBill(payload)
  ElMessage.success(`已保存采购单：${bill.sn}`)
  resetForm()
}

// 矩阵模式
const matrixVisible = ref(false)
const matrixForm = reactive({ styleNo: '', code: '', name: '', price: 0, colors: [], sizes: [] })
const matrixQtyMap = reactive({})

function openMatrix(){
  matrixForm.styleNo = ''
  matrixForm.code = ''
  matrixForm.name = ''
  matrixForm.price = 0
  matrixForm.colors = [...dict.colors]
  matrixForm.sizes = [...dict.sizes]
  // 初始化数量为0
  Object.keys(matrixQtyMap).forEach(k => delete matrixQtyMap[k])
  matrixForm.colors.forEach(c => {
    matrixForm.sizes.forEach(s => { matrixQtyMap[`${c}__${s}`] = 0 })
  })
  matrixVisible.value = true
}

watch(
  () => [matrixForm.colors.slice(), matrixForm.sizes.slice()],
  () => {
    const set = new Set(Object.keys(matrixQtyMap))
    // 为新组合补0，移除已取消的组合
    const validKeys = new Set()
    matrixForm.colors.forEach(c => {
      matrixForm.sizes.forEach(s => {
        const k = `${c}__${s}`
        validKeys.add(k)
        if (!set.has(k)) matrixQtyMap[k] = 0
      })
    })
    Object.keys(matrixQtyMap).forEach(k => { if (!validKeys.has(k)) delete matrixQtyMap[k] })
  },
  { deep: true }
)

function applyMatrix(){
  const combos = []
  matrixForm.colors.forEach(c => {
    matrixForm.sizes.forEach(s => {
      const k = `${c}__${s}`
      const q = Number(matrixQtyMap[k] || 0)
      if (q > 0) {
        combos.push({ color: c, size: s, qty: q })
      }
    })
  })
  if (!combos.length) { ElMessage.warning('请填写数量'); return }
  combos.forEach(x => {
    items.value.push({
      code: matrixForm.code,
      name: matrixForm.name,
      styleNo: matrixForm.styleNo,
      color: x.color,
      size: x.size,
      qty: x.qty,
      price: Number(matrixForm.price || 0),
    })
  })
  matrixVisible.value = false
}
</script>

<style scoped>
.page-wrap { padding: 16px; }
.toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; gap: 12px; }
.actions { display: flex; gap: 12px; }
.mb-12 { margin-bottom: 12px; }
.detail-toolbar { display: flex; gap: 12px; margin-bottom: 12px; }
.summary { display: flex; gap: 24px; justify-content: flex-end; padding: 10px 0; }
.w-240 { width: 240px; }
.w-160 { width: 160px; }
.w-220 { width: 220px; }
.ml-8 { margin-left: 8px; }
.text-muted { color: #6b7280; font-size: 12px; }
.matrix-head { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; }
.matrix-pick { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.mt-12 { margin-top: 12px; }
</style>


 